const jwt = require('jsonwebtoken')

const { createUser, getUserinfo, updateById } = require('../service/user.service')

const { userRegiisterError, updatePassError } = require('../constant/err.type')

const { JWT_SECRET } = require('../config/config.default')
const { body } = require('koa/lib/response')

class UserController {
  async register(ctx, next) {
    // console.log(ctx.request.body);
    const { user_name, password } = ctx.request.body
    try {
      // 操作数据库
      const res = await createUser(user_name, password)
      // console.log(res);
      ctx.body = {
        code: 0,
        message: '用户注册成功',
        result: {
          id: res.id,
          user_name: res.user_name,
        }
      }
    } catch (err) {
      console.log('用户注册错误');
      ctx.app.emit('error', userRegiisterError, ctx)
    }

  }
  async login(ctx, next) {
    const { user_name } = ctx.request.body

    try {
      const { password, ...res } = await getUserinfo({ user_name })
      ctx.body = {
        code: 0,
        message: '用户登录成功',
        result: {
          token: jwt.sign(res, JWT_SECRET, { expiresIn: '1d' })
        }
      }
    } catch (err) {
      console.error("用户登录失败", err);
    }

  }
  async changePassword(ctx, next) {
    const id = ctx.state.user.id
    const password = ctx.request.body.password
    // console.log(id, password);
    try {
      const res = await updateById({ id, password })
      if (res) {
        ctx.body = {
          code: 0,
          message: '修改密码成功',
          result: '',
        }
      }
    } catch (err) {
      console.log('修改密码失败', err);
      ctx.app.emit('error', updatePassError, ctx)
    }

  }
}

module.exports = new UserController()